package com.zhkj.txg.module.mine.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.contrarywind.interfaces.IPickerViewData
import com.zhkj.lib.base.UserInfoChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.module.home.popup.SelectedGenderDialog
import com.zhkj.txg.module.mine.popup.ChangeUserNamePopupWindow
import com.zhkj.txg.module.mine.vm.MineViewModel
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.MatisseUtils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_edit_user.*
import java.text.SimpleDateFormat
import java.util.*

class EditUserInfoActivity : ViewModelActivity<MineViewModel>() {

    companion object {
        fun start(activity: Activity) {
            val intent = Intent(activity, EditUserInfoActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun setViewModel(): MineViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleUserInfo
    override val layoutResId: Int = R.layout.activity_edit_user

    private val requestCodeGallery = 1020
    private val datePatten = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

    // 修改昵称的popupWindow
    private val nickNamePopupWindow: ChangeUserNamePopupWindow by lazy {
        ChangeUserNamePopupWindow(this) {
            nickNamePopupWindow.dismiss()
            // 将确认修改的名字存入数据
            viewModel.userInfo?.nickname = it
            viewModel.editUserInfo(AccountManager.getToken(), viewModel.userInfo?.avatar ?: "")
        }
    }

    // 修改生日的picker
    private val datePicker: TimePickerView by lazy {
        TimePickerBuilder(this) { date, _ ->
            datePicker.dismiss()
            // 将修改的时间存入数据
            viewModel.userInfo?.birthday = datePatten.format(date)
            viewModel.editUserInfo(AccountManager.getToken(), viewModel.userInfo?.avatar ?: "")
        }.setType(booleanArrayOf(true, true, true, false, false, false))
            .setTitleText(getString(R.string.birthday)).build()
    }

    // 修改性别的popupWindow
    private val genderPopupWindow: SelectedGenderDialog by lazy {
        SelectedGenderDialog(this) {
            genderPopupWindow.dismiss()
            viewModel.userInfo?.gender = if (it) "男" else "女"
            viewModel.editUserInfo(AccountManager.getToken(), viewModel.userInfo?.avatar ?: "")
        }
    }

    // 修改省市区的picker
    private val areaOption: OptionsPickerView<IPickerViewData> by lazy {
        OptionsPickerBuilder(this) { options1, options2, options3, _ ->
            // 数据填充
            viewModel.provinceList?.let { list ->
                viewModel.userInfo?.let {
                    val provinceEntity = list[options1]
                    val cityEntity = provinceEntity.cityList[options2]
                    val areaEntity = cityEntity.areaList[options3]
                    it.province = provinceEntity.provinceId
                    it.city = cityEntity.cityId
                    it.district = areaEntity.id
                    it.area =
                        provinceEntity.provinceName + cityEntity.cityName + areaEntity.areaName
                    viewModel.editUserInfo(
                        AccountManager.getToken(),
                        viewModel.userInfo?.avatar ?: ""
                    )
                }
            }
        }.build<IPickerViewData>()
    }

    override fun initUI() {
        ivUserAvatar.setOnClickListener {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, { selectPicture() }, {
                toast(getString(R.string.read_permission_deny))
            })
        }
        tvUserNickname.setOnClickListener {
            nickNamePopupWindow.showPopupWindow()
            nickNamePopupWindow.setOriginNickname(tvUserNickname.text.toString())
        }
        tvUserBirthday.setOnClickListener {
            tvUserBirthday.text.let { birthday ->
                if (birthday.isNotEmpty()) {
                    datePatten.parse(birthday.toString())?.let {
                        val calendar = Calendar.getInstance()
                        calendar.time = it
                        datePicker.setDate(calendar)
                        datePicker.show()
                    }
                } else datePicker.show()
            }
        }
        tvUserGender.setOnClickListener {
            genderPopupWindow.showPopupWindow()
        }
        tvUserArea.setOnClickListener {
            areaOption.setPicker(
                viewModel.provinceUIData?.provinceUIList,
                viewModel.provinceUIData?.cityUIList,
                viewModel.provinceUIData?.areaUIList
            )
            areaOption.show()
        }
    }

    override fun initData() {
        viewModel.getProvinceFromAssets()
        viewModel.userCenter(AccountManager.getToken()).takeIf {
            !it.hasObservers()
        }?.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.userInfo?.let { info ->
                viewModel.userInfo = info
                ImageUtils.loadCircleImage(this, ivUserAvatar, info.avatar)
                tvUserNickname.text = info.nickname
                tvUserBirthday.text = info.birthday
                tvUserGender.text = info.gender
                tvUserArea.text = info.area
                tvUserVipLimit.text = info.memberDate
                tvUserVipGrade.text = info.userCard.name
            }
        })
    }

    override fun initViewModel() {
        // 修改用户信息观察者
        viewModel.editUserInfoLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let { data ->
                // 用户数据刷新
                RxBus.post(UserInfoChangeEvent())
                // 数据刷新
                viewModel.userInfo?.let { userInfo ->
                    if (!data.userAvatar.isNullOrEmpty()) userInfo.avatar = data.userAvatar ?: ""
                    ImageUtils.loadCircleImage(this, ivUserAvatar, userInfo.avatar)
                    tvUserNickname.text = userInfo.nickname
                    tvUserBirthday.text = userInfo.birthday
                    tvUserGender.text = userInfo.gender
                    tvUserArea.text = userInfo.area
                    tvUserVipLimit.text = userInfo.memberDate
                    tvUserVipGrade.text = userInfo.userCard.name
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == requestCodeGallery) // 上传图片
            Matisse.obtainPathResult(data).takeIf {
                it.isNotEmpty()
            }?.run {
                viewModel.uploadAvatar(get(0))
            }?.takeIf {
                !it.hasObservers()
            }?.observe(this, Observer { response ->
                handlerResponseStatus(response.status, response.statusTip)
                if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                    viewModel.editUserInfo(AccountManager.getToken(), it.url, uploadAvatar = true)
                }
            })
    }

    /**
     * 打开图片选择器
     */
    private fun selectPicture() {
        MatisseUtils.selectPicture(this, requestCodeGallery)
    }
}